package server;

import java.util.Scanner;
import java.util.Set;

public class ConsoleListener extends Thread {

	private boolean isRunning;
	
	public ConsoleListener() {
		
	}
	
	@Override
	public synchronized void start() {
		isRunning = true;
		
		super.start();
	}
	
	@Override
	public void run() {
		Scanner scanner = new Scanner(System.in);
		
		String message;
		
		while(isRunning && (message = scanner.nextLine()) != null) {
			parseMessage(message);
		}
		
		scanner.close();
	}
	
	private void parseMessage(String message) {
		String m = message.trim();
		if(m.matches("exit")) {
			isRunning = false;
			Connection.get().close();
		} else if(m.matches("(pc|list)")) {
			Connection.get().printClients();
		} else if(m.matches("(sa|sendAll) .*")) {
			System.out.println("-send to all: " + message);
			
			Connection.get().broadcast(m.substring(3));
		} else if(m.matches("help")) {
			System.out.println("-exit - close program");
			System.out.println("-help - shows all commands");
			System.out.println("-pc|list - print clients");
			System.out.println("-sa|sendAll - send the followed message to all clients");
		} else if(m.matches("status")) {
			Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
			
			System.out.println("currently running " + threadSet.size() + " threads: ");
			for(Thread t: threadSet) {
				System.out.println("- " + t.getName() + "(id=" + t.getId() + "): ");
			}
		} else {
			System.out.println("Unknown command!");
		}
	}
}
